import { createRouter, createWebHashHistory } from 'vue-router';
import { defineAsyncComponent } from 'vue';
import { getToken } from '../util/authToken';
import whiteNames from './whiteRouterList';

import mobileLayout from '../mobileLayout.vue';
const Home = defineAsyncComponent(() =>
  import('../pages/home/index.vue')
);
const Book = defineAsyncComponent(() =>
  import('../pages/book/index.vue')
);
const BookEdit = defineAsyncComponent(() =>
  import('../pages/book/edit.vue')
);
const Memo = defineAsyncComponent(() =>
  import('../pages/memo/index.vue')
);
const MemoEdit = defineAsyncComponent(() =>
  import('../pages/memo/edit/index.vue')
);
const Mine = defineAsyncComponent(() =>
  import('../pages/mine/index.vue')
);
const Search = defineAsyncComponent(() =>
  import('../pages/search/index.vue')
);
const SetSystemColor = defineAsyncComponent(() =>
  import('../pages/mine/setSystemColor.vue')
);
const Login = defineAsyncComponent(() =>
  import('../pages/login/index.vue')
);
const Register = defineAsyncComponent(() =>
  import('../pages/register/index.vue')
);

const NotFound = defineAsyncComponent(() =>
  import('../components/NotFound.vue')
);

const routes = [
  {
    path: '',
    redirect: '/index/home',
  },
  {
    path: '/index',
    component: mobileLayout,
    children: [
      {
        path: 'home',
        name:'Home',
        component:Home
      },
      {
        path: 'book',
        name:'Book',
        component:Book
      },
      {
        path: 'memo',
        name:'Memo',
        component:Memo
      },
      {
        path: 'mine',
        component:Mine
      }
    ],
  },
  {
    path: '/bookEdit',
    name:'BookEdit',
    component:BookEdit
  },
  {
    path: '/memoEdit',
    name:'MemoEdit',
    component:MemoEdit
  },
  {
    path: '/search',
    name:'Search',
    component:Search
  },
  {
    path: '/setSystemColor',
    name:'SetSystemColor',
    component:SetSystemColor
  },
  {
    path: '/login',
    name:'Login',
    component:Login
  },
  {
    path: '/register',
    name:'Register',
    component:Register
  },
  { path: '/:pathMatch(.*)*', component: NotFound },
];

const router = createRouter({
    // 再electron 打包时候要使用 hash模式
    history: createWebHashHistory(),
    routes
})

router.beforeEach((to, from) => {
  if (whiteNames.includes(to.name)) return true;
  if (!getToken()) {
      return to.name !== 'Login' ? { name: 'Login' } : true;
  } else {
      return to.name === 'Login' ? { path: '/' } : true;
  }
});



export default router;